import { Space, Table, Card, Form, Input, Button, Select } from 'antd'
import { SearchOutlined } from '@ant-design/icons'
import { useEffect, useState } from 'react'
import {
  IhospitalListItem,
  IhospitalListsType,
  ProvinceItem,
  ProvinceList,
} from '@api/hospital/model/hospitalListTypes'
import {
  reqHospitalLists,
  reqCodeLists,
  reqDictLists,
  reqUpdateStatus,
} from '@api/hospital/hospitalList'
import { useNavigate } from 'react-router-dom'
const { Option } = Select

export default function HospitalList() {
  const [form] = Form.useForm()
  const [hospitalListsLs, setHospitalListsLs] = useState<IhospitalListsType>([])
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(5)
  const [total, setTotal] = useState(5)
  const [loading, setLoading] = useState(false)
  const [provinceLists, setProvinceLists] = useState<ProvinceList>([])
  const [cityLists, setCityLists] = useState<ProvinceList>([])
  const [districtLists, setDistrictLists] = useState<ProvinceList>([])
  const [hostypeLists, setHostypeLists] = useState<ProvinceList>([])
  const [ploading, setPloading] = useState(false)
  const [cloading, setCloading] = useState(false)
  const [dloading, setDloading] = useState(false)
  const [tloading, setTloading] = useState(false)
  const navigate = useNavigate()

  const columns = [
    {
      title: '序号',
      align: 'center' as 'center',
      render: (text: any, record: any, index: number) => index + 1,
    },
    {
      title: '医院logo',
      dataIndex: 'logoData',
      render: (logo: string) => (
        <img
          style={{ width: 100, height: 100 }}
          className="hospital-img"
          src={'data:image/jpeg;base64,' + logo}
          alt="logo"
        />
      ),
    },
    {
      title: '医院名称',
      dataIndex: 'hosname',
    },
    {
      title: '等级',
      render: (text: any, record: IhospitalListItem) =>
        record.param.hostypeString,
    },
    {
      title: '详细地址',
      render: (text: any, record: IhospitalListItem) =>
        record.param.fullAddress,
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (text: number) => (text ? '已上线' : '未上线'),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title: '操作',
      render: (text: IhospitalListItem) => {
        return (
          <Space>
            <Button
              type="primary"
              onClick={() => {
                navigate(`/syt/hospital/hospitalList/show/${text.id}`)
              }}
            >
              查看
            </Button>
            <Button
              type="primary"
              onClick={() => {
                navigate(`/syt/hospital/hospitalList/schedule/` + text.hoscode)
              }}
            >
              排班
            </Button>
            <Button type="primary" onClick={updateStatus(text.id, text.status)}>
              {text.status ? '下线' : '上线'}
            </Button>
          </Space>
        )
      },
    },
  ]

  async function getHospitalLists(page: number, pageSize: number) {
    setLoading(true)
    const {
      hosname,
      hoscode,
      hostype,
      provinceCode,
      cityCode,
      districtCode,
      status,
    } = form.getFieldsValue()
    const result = await reqHospitalLists({
      page,
      limit: pageSize,
      hosname,
      hoscode,
      hostype,
      provinceCode,
      cityCode,
      districtCode,
      status,
    })
    setLoading(false)
    setHospitalListsLs(result.content)
    setPage(page)
    setPageSize(pageSize)
    setTotal(result.totalElements)
  }

  async function getProvinceLists(dictCode: string) {
    setPloading(true)
    const result = await reqCodeLists(dictCode)
    setProvinceLists(result)
    setPloading(false)
  }

  async function getCityLists(cityId: string) {
    setCloading(true)
    const result = await reqDictLists(cityId)
    setCityLists(result)
    setCloading(false)
  }

  async function getDistrictLists(districtId: string) {
    setDloading(true)
    const result = await reqDictLists(districtId)
    setDistrictLists(result)
    setDloading(false)
  }

  async function getHostypeLists(dictCode: string) {
    setTloading(true)
    const result = await reqCodeLists(dictCode)
    setHostypeLists(result)
    setTloading(false)
  }

  //更新上线/下线状态函数
  const updateStatus = (id: string, status: number) => async () => {
    if (status === 1) {
      await reqUpdateStatus(id, 0)
    } else {
      await reqUpdateStatus(id, 1)
    }
    getHospitalLists(page, pageSize)
  }

  useEffect(() => {
    getHospitalLists(page, pageSize)
    getProvinceLists('Province')
    getHostypeLists('Hostype')
  }, [])

  return (
    <Card>
      <Space direction="vertical" size={'large'}>
        <Form layout="inline" form={form}>
          <Form.Item name="provinceCode" style={{ width: 200 }}>
            <Select
              loading={ploading}
              placeholder="请选择省"
              onChange={(value: string) => {
                getCityLists(value)
                setDistrictLists([])
                form.setFieldsValue({ cityCode: '', districtCode: '' })
              }}
            >
              {provinceLists.map((province: ProvinceItem) => {
                return (
                  <Option key={province.id} value={province.value}>
                    {province.name}
                  </Option>
                )
              })}
            </Select>
          </Form.Item>
          <Form.Item name="cityCode" style={{ width: 200 }}>
            <Select
              loading={cloading}
              placeholder="请选择市"
              onChange={(value: string) => {
                getDistrictLists(value)
              }}
            >
              {cityLists.map((cityItem: ProvinceItem) => {
                return (
                  <Option value={cityItem.value} key={cityItem.id}>
                    {cityItem.name}
                  </Option>
                )
              })}
            </Select>
          </Form.Item>
          <Form.Item name="districtCode" style={{ width: 200 }}>
            <Select placeholder="请选择区" loading={dloading}>
              {districtLists.map((district: ProvinceItem) => {
                return (
                  <Option key={district.id} value={district.value}>
                    {district.name}
                  </Option>
                )
              })}
            </Select>
          </Form.Item>
          <Form.Item name="hosname" style={{ width: 200 }}>
            <Input placeholder="医院名称" />
          </Form.Item>
          <Form.Item name="hoscode" style={{ width: 200 }}>
            <Input placeholder="医院编号" />
          </Form.Item>
          <Form.Item name="hostype" style={{ width: 200, marginTop: 20 }}>
            <Select placeholder="医院类型" loading={tloading}>
              {hostypeLists.map((item: ProvinceItem) => {
                return <Option value={item.value}>{item.name}</Option>
              })}
            </Select>
          </Form.Item>
          <Form.Item name="status" style={{ width: 200, marginTop: 20 }}>
            <Select placeholder="医院状态">
              <Option value="1">已上线</Option>
              <Option value="0">未上线</Option>
            </Select>
          </Form.Item>
          <Form.Item style={{ marginTop: 20 }}>
            <Button
              type="primary"
              icon={<SearchOutlined />}
              onClick={() => {
                getHospitalLists(1, pageSize)
              }}
            >
              查询
            </Button>
          </Form.Item>
          <Form.Item style={{ marginTop: 20 }}>
            <Button
              onClick={() => {
                form.resetFields()
                getHospitalLists(page, pageSize)
              }}
            >
              清空
            </Button>
          </Form.Item>
        </Form>
        <Table
          rowKey="id"
          columns={columns}
          dataSource={hospitalListsLs}
          bordered
          loading={loading}
          pagination={{
            current: page,
            pageSize,
            total,
            showQuickJumper: true,
            showSizeChanger: true,
            pageSizeOptions: ['2', '5', '10'],
            onChange: getHospitalLists,
            showTotal: (total) => `总共 ${total} 条`,
          }}
        />
      </Space>
    </Card>
  )
}
